﻿using Newtonsoft.Json;
using PMIS.Common.Dialog;
using PMIS.Controls;
using PMIS.HttpRequest;
using PMIS.Shared.DTO;
using PMIS.Shared.Models;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace PMIS.ViewModels.Department
{
    public class AddEditDeptViewModel : DialogViewModelBase
    {
        private readonly HttpService _httpService;

        private List<DepartmentDto> _allDeptList;

        public AddEditDeptViewModel(HttpService httpService)
        {
            _httpService = httpService;

            this.Dept = new DepartmentDto();

            LoadDeptList();
        }

        private DepartmentDto _dept;

        public DepartmentDto Dept
        {
            get
            {
                return _dept;
            }
            set
            {
                SetProperty(ref _dept, value);
            }
        }

        private ICommand _saveCommand;
        public ICommand SaveCommand
        {
            get
            {
                if (_saveCommand == null)
                {
                    _saveCommand = new DelegateCommand(OnSave);
                }
                return _saveCommand;
            }
        }

        private ICommand _cancelCommand;
        public ICommand CancelCommand
        {
            get
            {
                if (_cancelCommand == null)
                {
                    _cancelCommand = new DelegateCommand(OnCancel);
                }
                return _cancelCommand;
            }
        }

        private async void OnSave()
        {
            bool result = false;
            if (string.IsNullOrEmpty(this.Dept.Id))
            {
                result = await Add();
            }
            else
            {
                result = await Edit();
            }

            if (result)
            {
                CloseDialog(new DialogResult(ButtonResult.OK));
            }
            else
            {
                ToastManager.ShowToast("保存失败");
            }
        }

        private async Task<bool> Add()
        {
            if (_selectedDeptItem != null)
            {
                _dept.ParentId = _selectedDeptItem?.Id;
            }
            var response = await _httpService.PostAsync(Api.DEPT_ADD, _dept);
            if (response?.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        private async Task<bool> Edit()
        {
            if (_selectedDeptItem != null)
            {
                _dept.ParentId = _selectedDeptItem?.Id;
            }
            var response = await _httpService.PutAsync(Api.DEPT_UPDATE, _dept);
            if (response?.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        private void OnCancel()
        {
            CloseDialog(new DialogResult(ButtonResult.Cancel));
        }

        public override void OnDialogOpened(IDialogParameters parameters)
        {
            if (parameters.Count > 0)
            {
                this.Title = "编辑部门";
                this.Dept = parameters.GetValue<DepartmentDto>("data");
            }
            else
            {
                this.Title = "新建部门";
            }
        }

        private async void LoadDeptList()
        {
            var response = await _httpService.GetAsync(Api.DEPT_GET_LIST);
            if (response?.code == 1)
            {
                var data = JsonConvert.DeserializeObject<PagingModel<DepartmentDto>>(JsonConvert.SerializeObject(response.data));
                _allDeptList = data?.Items.OrderBy(p => p.Sort).ToList();
                DeptItems = new ObservableCollection<DepartmentDto>(_allDeptList.Where(x => x.ParentId == null));
                foreach (var item in DeptItems)
                {
                    LoadChildDept(item);
                }
            }
        }

        public void LoadChildDept(DepartmentDto dept)
        {
            dept.Children = _allDeptList.Where(x => x.ParentId == dept.Id).ToList();
            foreach (var subitem in dept.Children)
            {
                // Recursive call
                LoadChildDept(subitem);
            }
        }

        private ObservableCollection<DepartmentDto> _deptItems;
        public ObservableCollection<DepartmentDto> DeptItems
        {
            get => _deptItems;
            set { SetProperty(ref _deptItems, value); }
        }

        private DepartmentDto _selectedDeptItem;
        public DepartmentDto SelectedDeptItem
        {
            get => _selectedDeptItem;
            set { SetProperty(ref _selectedDeptItem, value); }
        }
    }
}
